package controllers

import (
	"crypto/md5"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"zk3/models"
)

type UserController struct {
	beego.Controller
}

type ReturnMsg struct {
	Code string
	Msg  string
	Data interface{}
}

func (c *UserController) Register() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET")
	Username := c.GetString("Username")
	Password := c.GetString("Password")

	user := models.User{
		Username: Username,
		Password: Password,
	}

	models.DB.Where("username = ? And password", Username, Password).Create(&user)

	c.Data["json"] = ReturnMsg{"200", "注册成功", user}
	c.ServeJSON(true)
}
func (c *UserController) Login() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "POST")

	Username := c.GetString("username")
	Password := c.GetString("Password")

	user := models.User{
		Username: Username,
		Password: Password,
	}

	get := models.Client.Get("logError" + Username).Val()
	if get >= "3" {
		c.Data["json"] = ReturnMsg{"500", "密码错误3次,禁止登录3分钟", nil}
		c.ServeJSON(true)
		return
	}

	models.DB.Find(&user)

	if user.ID == 0 {
		c.Data["json"] = ReturnMsg{"500", "ID不存在", nil}
		c.ServeJSON(true)
		return
	}

	if user.Password != Password {

		incr := models.Client.Incr("loginErr" + Username)
		if incr.Val() >= 3 {
			models.Client.Set("loginErr"+Username, time.Now().Add(3*time.Minute).Unix(), 3*time.Minute)

		}
		c.Data["json"] = ReturnMsg{"500", "密码不正确", nil}
		c.ServeJSON(true)
		return
	}

	c.Data["json"] = ReturnMsg{"200", "登录成功", user}
	c.ServeJSON(true)
}
func (c *UserController) Update() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET")
	username := c.GetString("username")
	password := c.GetString("Password")
	newPassword := c.GetString("newPassword")

	user := models.User{
		Username:    username,
		Password:    password,
		NewPassword: newPassword,
	}

	models.DB.Where("username = ?", username).Find(&user)

	if user.ID == 0 {
		c.Data["json"] = ReturnMsg{"500", "ID不存在", nil}
		c.ServeJSON(true)
		return
	}
	if user.Password != newPassword {
		c.Data["json"] = ReturnMsg{"500", "密码不正确", nil}
		c.ServeJSON(true)
		return
	}

	user.Password = newPassword
	models.DB.Debug().Model(&user).Updates(&user)
	c.Data["json"] = ReturnMsg{"200", "修改成功", user}
	c.ServeJSON(true)
}
func Md5string(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	return fmt.Sprintf("%x", has) //将[]byte转成16进制
}
